package com.bndg.browser.ui

import android.app.AlertDialog
import android.content.Intent
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bndg.browser.R
import com.bndg.browser.db.AppDatabase
import com.bndg.browser.db.History
import com.hjq.base.BaseActivity
import com.hjq.base.BaseAdapter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import timber.log.Timber

class HistoryActivity : BaseActivity() {
    private val rvList: RecyclerView? by lazy { findViewById(R.id.recyclerView) }
    override fun getLayoutId(): Int {
        return R.layout.activity_history
    }

    private var historyAdapter: HistoryAdapter? = null

    override fun initView() {
        historyAdapter = HistoryAdapter(this)
        historyAdapter?.setOnItemClickListener(object : BaseAdapter.OnItemClickListener {
            override fun onItemClick(recyclerView: RecyclerView?, itemView: View?, position: Int) {
                val history = historyAdapter?.getItem(position)
                val mainBrowserIntent = Intent()
                    .setClass(this@HistoryActivity, CommonActivity::class.java)
                    .putExtra("input", history?.url)
                startActivity(mainBrowserIntent)
            }
        })
        rvList?.adapter = historyAdapter
//        rvList?.setHasFixedSize(true)
        // 设置 Toolbar 为 ActionBar
        val toolbar = findViewById<Toolbar>(R.id.toolbar)
        setSupportActionBar(toolbar)
        // 可选：启用返回按钮
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_history, menu)
        return true
    }

    // 处理返回按钮点击事件
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            onBackPressed()
            return true
        } else if (item.itemId == R.id.action_clear) {
            // 弹出alertdialog提示
            val builder = AlertDialog.Builder(this)
            builder.setTitle("提示")
            builder.setMessage("确定要清空历史记录吗？")
            builder.setPositiveButton("确定") { _, _ ->
                // 清空历史记录
                lifecycleScope.launch(Dispatchers.IO) {
                    AppDatabase.getInstance(this@HistoryActivity)
                        .historyDao()
                        .deleteAll()
                }
                historyAdapter?.clearData()
            }
            builder.setNegativeButton("取消") { _, _ -> }
            builder.show()
        }
        return super.onOptionsItemSelected(item)
    }

    override fun initData() {
        val all = mutableListOf<History>()
        lifecycleScope.launch(Dispatchers.IO) {
            all.addAll(
                AppDatabase.getInstance(this@HistoryActivity)
                    .historyDao()
                    .getAll()
            )
        }
        Timber.d("all: ${all.size}")
        historyAdapter?.setData(all)
    }

}
